//
//  CustomViewController.swift
//  DiffableDataSource
//
//  Created by bin hu on 2025/6/3.
//

import UIKit

class SectionHeaderView: UITableViewHeaderFooterView {
    static let identifier = "SectionHeaderView"
    
    var buttonAction: (() -> Void)?
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 20)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    private lazy var actionButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("操作", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        button.backgroundColor = .systemBlue
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 14
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        contentView.backgroundColor = .systemGroupedBackground
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(actionButton)
        
        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            titleLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            
            actionButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            actionButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            actionButton.widthAnchor.constraint(equalToConstant: 70),
            actionButton.heightAnchor.constraint(equalToConstant: 28)
        ])
    }
    
    func configure(title: String, buttonTitle: String, action: (() -> Void)? = nil) {
        titleLabel.text = title
        actionButton.setTitle(buttonTitle, for: .normal)
        buttonAction = action
    }
    
    @objc private func buttonTapped() {
        buttonAction?()
    }
}

enum CustomSection: CaseIterable {
    case fruits
    case vegetables
    case desserts
    
    var title: String {
        switch self {
        case .fruits: return "水果"
        case .vegetables: return "蔬菜"
        case .desserts: return "甜点"
        }
    }
    
    var buttonTitle: String {
        switch self {
        case .fruits: return "添加"
        case .vegetables: return "编辑"
        case .desserts: return "更多"
        }
    }
    
    var items: [CustomItem] {
        switch self {
        case .fruits:
            return [
                CustomItem(title: "苹果", emoji: "🍎"),
                CustomItem(title: "香蕉", emoji: "🍌"),
                CustomItem(title: "橙子", emoji: "🍊")
            ]
        case .vegetables:
            return [
                CustomItem(title: "胡萝卜", emoji: "🥕"),
                CustomItem(title: "西兰花", emoji: "🥦"),
                CustomItem(title: "西红柿", emoji: "🍅")
            ]
        case .desserts:
            return [
                CustomItem(title: "蛋糕", emoji: "🍰"),
                CustomItem(title: "冰淇淋", emoji: "🍦"),
                CustomItem(title: "糖果", emoji: "🍬")
            ]
        }
    }
}

struct CustomItem: Hashable {
    let id = UUID()
    let title: String
    let emoji: String
    
    var displayTitle: String {
        "\(emoji) \(title)"
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    
    static func == (lhs: CustomItem, rhs: CustomItem) -> Bool {
        lhs.id == rhs.id
    }
}

class CustomViewController: UIViewController {
    
    private var tableView: UITableView!
    private var dataSource: UITableViewDiffableDataSource<CustomSection, CustomItem>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        configureDataSource()
        applyInitialSnapshot()
        
        // 设置导航栏
        title = "食品分类"
        navigationController?.navigationBar.prefersLargeTitles = true
    }
    
    private func setupUI() {
        // 创建表格视图
        tableView = UITableView(frame: view.bounds, style: .grouped)
        tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(SectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderView.identifier)
        tableView.delegate = self
        tableView.rowHeight = 60
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        
        // 添加底部视图
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 60))
        footerView.backgroundColor = .systemGroupedBackground
        
        let footerLabel = UILabel()
        footerLabel.text = "总计: \(CustomSection.allCases.flatMap { $0.items }.count) 个项目"
        footerLabel.textAlignment = .center
        footerLabel.font = UIFont.italicSystemFont(ofSize: 16)
        footerLabel.textColor = .gray
        footerLabel.frame = footerView.bounds
        footerView.addSubview(footerLabel)
        
        tableView.tableFooterView = footerView
    }
    
    private func configureDataSource() {
        dataSource = UITableViewDiffableDataSource(tableView: tableView) {
            tableView, indexPath, item in
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            
            // 配置单元格
            if #available(iOS 14.0, *) {
                var content = cell.defaultContentConfiguration()
                content.text = item.displayTitle
                content.textProperties.font = UIFont.systemFont(ofSize: 18)
                content.image = UIImage(systemName: "circle.fill")
                content.imageProperties.tintColor = indexPath.row % 2 == 0 ? .systemPurple : .systemGreen
                cell.contentConfiguration = content
            } else {
                // Fallback on earlier versions
            }
            
            // 设置背景
            let backgroundView = UIView()
            backgroundView.backgroundColor = .secondarySystemGroupedBackground
            backgroundView.layer.cornerRadius = 10
            cell.backgroundView = backgroundView
            
            // 设置选中背景
            let selectedView = UIView()
            selectedView.backgroundColor = .systemGray5
            selectedView.layer.cornerRadius = 10
            cell.selectedBackgroundView = selectedView
        
            return cell
        }
    }
    
    private func applyInitialSnapshot() {
        var snapshot = NSDiffableDataSourceSnapshot<CustomSection, CustomItem>()
        snapshot.appendSections(CustomSection.allCases)
        
        for section in CustomSection.allCases {
            snapshot.appendItems(section.items, toSection: section)
        }
        
        dataSource.apply(snapshot, animatingDifferences: false)
    }
    
    // 处理按钮动作
    private func handleSectionButtonAction(for section: CustomSection) {
        let title = "\(section.title)区操作"
        let message = "您点击了 \(section.buttonTitle) 按钮"
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

extension CustomViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard let section = CustomSection.allCases[safe: section] else { return nil }
        
        let header = tableView.dequeueReusableHeaderFooterView(
            withIdentifier: SectionHeaderView.identifier
        ) as? SectionHeaderView
        
        header?.configure(
            title: section.title,
            buttonTitle: section.buttonTitle
        ) { [weak self] in
            self?.handleSectionButtonAction(for: section)
        }
        
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if let item = dataSource.itemIdentifier(for: indexPath) {
//            let detailVC = UIViewController()
//            detailVC.view.backgroundColor = .white
//            
//            let label = UILabel()
//            label.text = "您选择了: \(item.displayTitle)"
//            label.font = UIFont.systemFont(ofSize: 24, weight: .bold)
//            label.textAlignment = .center
//            label.frame = detailVC.view.bounds
//            detailVC.view.addSubview(label)
//            self.present(detailVC, animated: true)
            print("您选择了: \(item.displayTitle)")
            navigationController?.pushViewController(CollectionViewController(), animated: true)
        }
    }
}

// 数组安全访问扩展
extension Collection {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
